package com.zmn.plat.utils.bean;

import lombok.extern.log4j.Log4j2;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * @author tanbiao
 * @description
 * @modifier
 * @since 2019/12/24 13:55
 **/
@Log4j2
public class BeanCopyUtils {

    /**
     * 功能描述 ：对象间的拷贝
     *
     * @param source：被拷贝的对象
     * @param target：返回目标对象
     * @return void
     * @author tanbiao
     * @modifier
     * @since 2020/6/18
     */
    public static <T, K> void copyProperties(T source, K target) {
        if (Objects.isNull(source) || Objects.isNull(target)) {
            return;
        }
        BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), false);
        copier.copy(source, target, null);
    }


    /**
     * 功能描述 ：对象间的拷贝
     *
     * @param source：被拷贝的对象类
     * @param target：目标对象类
     * @param sourceList：被拷贝的对象集合
     * @param copyer：目标对象的创建函数如new
     * @return List
     * @author tanbiao
     * @modifier
     * @since 2020/6/18
     */
    public static <T, K> List<K> copyProperties(List<T> sourceList, Class<T> source, Class<K> target, Supplier<K> copyer) {
        if (!CollectionUtils.isEmpty(sourceList) && !Objects.isNull(source) && !Objects.isNull(target) && !Objects.isNull(copyer)) {
            List<K> retList = new ArrayList<>(sourceList.size());
            BeanCopier copier = BeanCopier.create(source, target, false);
            for (T sourceObj : sourceList) {
                K targetObject = copyer.get();
                copier.copy(sourceObj, targetObject, null);
                retList.add(targetObject);
            }
            return retList;
        }
        return Collections.EMPTY_LIST;
    }

}
